
import 'package:bookshelf/log/logger.dart';
import 'package:bot_toast/bot_toast.dart';
import 'package:event_bus/event_bus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';

import 'entity/current_task_entity.dart';
import 'entity/resort_entity.dart';
import 'entity/setting_entity.dart';
import 'http/api_url.dart';
import 'page/index_page.dart';
import 'reader/hf_serial_port_helper.dart';
import 'reader/reader_manager.dart';
import 'serial/serial_port_helper.dart';
import 'tts/tts_helper.dart';
import 'util/clock.dart';
import 'util/led_rule.dart';
import 'util/saver.dart';
import 'util/timer_manager.dart';


void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  tts = TtsHelper()..initTTS();
  // await LoggerManager().initLogger();
  eventFactory = EventBus();
  await GetStorage.init();


  FlutterError.onError = (FlutterErrorDetails details) async {
    Logger().write('${details.exception}\r\n${details.stack}\r\n');
  };

  final box = GetStorage();

  if(box.hasData('setting_entity')){
    settingEntity = SettingEntity.fromJson(box.read("setting_entity"));
    if(settingEntity.apiAddr != null){
      apiUrl = 'http://${settingEntity.apiAddr!}:60060';
      // sip2ApiUrl = 'http://${settingEntity.apiAddr!}:5006';
      faceUrl = 'http://${settingEntity.apiAddr!}:60060';
    }
  }else{
    settingEntity = SettingEntity();
  }

  try{
    if(settingEntity.ledSerial != null){
      ledSerialPortHelper = SerialPortHelper(settingEntity.ledSerial!,ledRule());
    }
  }catch(e){
    print(e);
  }
  try{
    if(settingEntity.idSerial != null){
      idSerialPortHelper = SerialPortHelper(settingEntity.idSerial!,19200);
    }
  }catch(e){
    print(e);
  }

  try{
    if(settingEntity.hfSerial != null && settingEntity.hfBaudRate != null){
      hfSerialPortHelper = HfSerialPortHelper(settingEntity.hfSerial!,int.parse(settingEntity.hfBaudRate!));
    }
  }catch(e){
    print(e);
  }

  timer = TimerManager()..setCountDownTime(actionTimeCountdown: settingEntity.actionTime);

  currentTask = CurrentTaskEntity();
  resort = ResortEntity();

  clock = Clock()..start();
  saver = Saver();

  runApp(const MyApp());

}



late EventBus eventFactory;
late SerialPortHelper ledSerialPortHelper;
late SerialPortHelper idSerialPortHelper;
late HfSerialPortHelper hfSerialPortHelper;
late SettingEntity settingEntity;
late TimerManager timer;
late Clock clock;
late Saver saver;
late TtsHelper tts;
late CurrentTaskEntity currentTask;
late ResortEntity resort;
bool canInventory = true;
ReaderManager readerManager = ReaderManager();


class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    if (Theme.of(context).platform == TargetPlatform.android) {
      SystemUiOverlayStyle style = const SystemUiOverlayStyle(statusBarColor: Colors.transparent);
      SystemChrome.setSystemUIOverlayStyle(style);
    }
    return  ScreenUtilInit(
      designSize: const Size(400, 711),
      minTextAdapt: true,
      splitScreenMode: true,
      builder: (_ , child) {
        return  GetMaterialApp(
            debugShowCheckedModeBanner: false,
            theme: ThemeData(
              fontFamily: 'simsun',
            ),
            routingCallback: (routing){
              // print('routing = ${routing!.current}');

              if(routing!.current == '/'){
                canInventory = true;
                saver.start();
                resort.upload();
              }else{
                if(routing.current == '/Setting'){
                  canInventory = false;
                }
                saver.cancel();
              }
            },
            builder: BotToastInit(),
            home: const Index()
        );
      },
    );
  }
}
